/**
 * 登录页面交互功能
 */

class LoginManager {
    constructor() {
        this.form = document.getElementById('loginForm');
        this.loginBtn = document.getElementById('loginBtn');
        this.loading = document.getElementById('loading');
        this.btnText = document.getElementById('btnText');
        this.usernameInput = document.getElementById('username');
        this.passwordInput = document.getElementById('password');
        this.rememberCheckbox = document.getElementById('remember');
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.loadRememberedCredentials();
        this.setupFormValidation();
        this.setupAccessibility();
        this.createParticles();
    }
    
    bindEvents() {
        // 表单提交事件
        this.form.addEventListener('submit', (e) => this.handleSubmit(e));
        
        // 输入框焦点效果
        document.querySelectorAll('.form-control').forEach(input => {
            input.addEventListener('focus', (e) => this.handleInputFocus(e));
            input.addEventListener('blur', (e) => this.handleInputBlur(e));
            input.addEventListener('input', (e) => this.handleInputChange(e));
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => this.handleKeydown(e));
        
        // 记住我功能
        this.rememberCheckbox.addEventListener('change', () => this.handleRememberChange());
        
        // 密码显示/隐藏功能
        this.setupPasswordToggle();
        
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => this.handleVisibilityChange());
    }
    
    handleSubmit(e) {
        if (!this.validateForm()) {
            e.preventDefault();
            return;
        }
        
        this.showLoading();
        this.saveCredentials();
        
        // 模拟网络延迟，实际项目中不需要
        setTimeout(() => {
            if (document.querySelector('.alert-danger')) {
                this.hideLoading();
            }
        }, 1000);
    }
    
    validateForm() {
        const username = this.usernameInput.value.trim();
        const password = this.passwordInput.value.trim();
        
        if (!username) {
            this.showError('请输入用户名');
            this.usernameInput.focus();
            return false;
        }
        
        if (!password) {
            this.showError('请输入密码');
            this.passwordInput.focus();
            return false;
        }
        
        if (username.length < 3) {
            this.showError('用户名至少需要3个字符');
            this.usernameInput.focus();
            return false;
        }
        
        if (password.length < 6) {
            this.showError('密码至少需要6个字符');
            this.passwordInput.focus();
            return false;
        }
        
        return true;
    }
    
    showError(message) {
        // 移除现有错误消息
        const existingAlert = document.querySelector('.alert-danger');
        if (existingAlert) {
            existingAlert.remove();
        }
        
        // 创建新的错误消息
        const alertDiv = document.createElement('div');
        alertDiv.className = 'alert alert-danger';
        alertDiv.innerHTML = `
            <i class="fas fa-exclamation-triangle me-2"></i>
            ${message}
        `;
        
        // 插入到表单前面
        this.form.insertBefore(alertDiv, this.form.firstChild);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 3000);
    }
    
    showLoading() {
        this.loading.style.display = 'inline-block';
        this.btnText.innerHTML = '登录中...';
        this.loginBtn.disabled = true;
        this.loginBtn.style.cursor = 'not-allowed';
    }
    
    hideLoading() {
        this.loading.style.display = 'none';
        this.btnText.innerHTML = '<i class="fas fa-sign-in-alt me-2"></i>立即登录';
        this.loginBtn.disabled = false;
        this.loginBtn.style.cursor = 'pointer';
    }
    
    handleInputFocus(e) {
        const formGroup = e.target.closest('.form-group');
        formGroup.classList.add('focused');
        
        // 清除错误状态
        e.target.classList.remove('is-invalid');
    }
    
    handleInputBlur(e) {
        const formGroup = e.target.closest('.form-group');
        if (!e.target.value.trim()) {
            formGroup.classList.remove('focused');
        }
    }
    
    handleInputChange(e) {
        // 实时验证
        const input = e.target;
        const value = input.value.trim();
        
        if (input.id === 'username' && value.length > 0 && value.length < 3) {
            input.classList.add('is-invalid');
        } else if (input.id === 'password' && value.length > 0 && value.length < 6) {
            input.classList.add('is-invalid');
        } else {
            input.classList.remove('is-invalid');
        }
    }
    
    handleKeydown(e) {
        // Enter键快速登录
        if (e.key === 'Enter' && document.activeElement.tagName === 'INPUT') {
            e.preventDefault();
            if (document.activeElement === this.usernameInput) {
                this.passwordInput.focus();
            } else if (document.activeElement === this.passwordInput) {
                this.form.dispatchEvent(new Event('submit'));
            }
        }
        
        // Escape键清除表单
        if (e.key === 'Escape') {
            this.clearForm();
        }
    }
    
    handleRememberChange() {
        if (!this.rememberCheckbox.checked) {
            localStorage.removeItem('rememberedUsername');
        }
    }
    
    handleVisibilityChange() {
        if (document.hidden) {
            // 页面隐藏时暂停动画
            document.querySelectorAll('.particle').forEach(particle => {
                particle.style.animationPlayState = 'paused';
            });
        } else {
            // 页面显示时恢复动画
            document.querySelectorAll('.particle').forEach(particle => {
                particle.style.animationPlayState = 'running';
            });
        }
    }
    
    loadRememberedCredentials() {
        const savedUsername = localStorage.getItem('rememberedUsername');
        if (savedUsername) {
            this.usernameInput.value = savedUsername;
            this.rememberCheckbox.checked = true;
            this.passwordInput.focus();
        } else {
            this.usernameInput.focus();
        }
    }
    
    saveCredentials() {
        if (this.rememberCheckbox.checked) {
            localStorage.setItem('rememberedUsername', this.usernameInput.value.trim());
        } else {
            localStorage.removeItem('rememberedUsername');
        }
    }
    
    clearForm() {
        this.usernameInput.value = '';
        this.passwordInput.value = '';
        this.rememberCheckbox.checked = false;
        this.usernameInput.focus();
        
        // 清除错误消息
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => alert.remove());
    }
    
    setupFormValidation() {
        // 添加CSS类用于验证状态
        const style = document.createElement('style');
        style.textContent = `
            .form-control.is-invalid {
                border-color: #dc3545;
                box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
            }
            
            .form-control.is-valid {
                border-color: #28a745;
                box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
            }
        `;
        document.head.appendChild(style);
    }
    
    setupAccessibility() {
        // 为表单元素添加ARIA标签
        this.usernameInput.setAttribute('aria-describedby', 'username-help');
        this.passwordInput.setAttribute('aria-describedby', 'password-help');
        
        // 添加屏幕阅读器友好的帮助文本
        const usernameHelp = document.createElement('div');
        usernameHelp.id = 'username-help';
        usernameHelp.className = 'sr-only';
        usernameHelp.textContent = '请输入您的用户名，至少3个字符';
        this.usernameInput.parentNode.appendChild(usernameHelp);
        
        const passwordHelp = document.createElement('div');
        passwordHelp.id = 'password-help';
        passwordHelp.className = 'sr-only';
        passwordHelp.textContent = '请输入您的密码，至少6个字符';
        this.passwordInput.parentNode.appendChild(passwordHelp);
    }
    
    setupPasswordToggle() {
        // 创建密码显示/隐藏按钮
        const toggleBtn = document.createElement('button');
        toggleBtn.type = 'button';
        toggleBtn.className = 'password-toggle';
        toggleBtn.innerHTML = '<i class="fas fa-eye"></i>';
        toggleBtn.setAttribute('aria-label', '显示密码');
        
        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .password-toggle {
                position: absolute;
                right: 45px;
                top: 50%;
                transform: translateY(-50%);
                background: none;
                border: none;
                color: #6c757d;
                cursor: pointer;
                padding: 5px;
                border-radius: 4px;
                transition: color 0.3s ease;
                z-index: 10;
            }
            
            .password-toggle:hover {
                color: #495057;
            }
            
            .password-toggle:focus {
                outline: 2px solid #667eea;
                outline-offset: 2px;
            }
        `;
        document.head.appendChild(style);
        
        // 添加到密码输入框容器
        const passwordGroup = this.passwordInput.closest('.form-group');
        passwordGroup.appendChild(toggleBtn);
        
        // 绑定点击事件
        toggleBtn.addEventListener('click', () => {
            const isPassword = this.passwordInput.type === 'password';
            this.passwordInput.type = isPassword ? 'text' : 'password';
            toggleBtn.innerHTML = isPassword ? '<i class="fas fa-eye-slash"></i>' : '<i class="fas fa-eye"></i>';
            toggleBtn.setAttribute('aria-label', isPassword ? '隐藏密码' : '显示密码');
        });
    }
    
    createParticles() {
        const particlesContainer = document.querySelector('.particles');
        if (!particlesContainer) return;
        
        // 根据屏幕大小调整粒子数量
        const particleCount = window.innerWidth < 768 ? 4 : 6;
        
        // 清除现有粒子
        particlesContainer.innerHTML = '';
        
        // 创建新粒子
        for (let i = 0; i < particleCount; i++) {
            const particle = document.createElement('div');
            particle.className = 'particle';
            
            // 随机大小和位置
            const size = Math.random() * 60 + 40; // 40-100px
            const left = Math.random() * 90 + 5; // 5-95%
            const delay = Math.random() * 6; // 0-6s
            
            particle.style.width = `${size}px`;
            particle.style.height = `${size}px`;
            particle.style.left = `${left}%`;
            particle.style.animationDelay = `${delay}s`;
            
            particlesContainer.appendChild(particle);
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new LoginManager();
});

// 页面加载动画
window.addEventListener('load', () => {
    document.body.style.opacity = '0';
    document.body.style.transition = 'opacity 0.5s ease';
    
    setTimeout(() => {
        document.body.style.opacity = '1';
    }, 100);
});

// 窗口大小变化时重新创建粒子
window.addEventListener('resize', () => {
    const loginManager = window.loginManager;
    if (loginManager && loginManager.createParticles) {
        loginManager.createParticles();
    }
});

// 导出给全局使用
window.LoginManager = LoginManager;